<template>
  <view class="container">
    <!-- 导航栏 -->

    <!-- 表单 -->
    <view class="form-container">
      <!-- 宠物选择 -->
      <view class="form-section">
        <view class="form-item">
          <text class="label">选择宠物<text class="required">*</text></text>
          <picker 
            :value="petIndex" 
            :range="pets" 
            range-key="name"
            @change="onPetChange"
            class="picker"
          >
            <view class="picker-text">
              {{ selectedPet ? selectedPet.name : '请选择宠物' }}
            </view>
          </picker>
        </view>
      </view>

      <!-- 记录信息 -->
      <view class="form-section">
        <view class="form-item">
          <text class="label">类型<text class="required">*</text></text>
          <picker 
            :value="typeIndex" 
            :range="recordTypeLabels" 
            @change="onTypeChange"
            class="picker"
          >
            <view class="picker-text">
              {{ formData.recordType || '请选择类型' }}
            </view>
          </picker>
        </view>

        <view class="form-item">
          <text class="label">内容<text class="required">*</text></text>
          <textarea 
            v-model="formData.title" 
            placeholder="请输入内容" 
            class="textarea content-textarea"
            maxlength="500"
          />
        </view>

        <view class="form-item">
          <text class="label">健康日期<text class="required">*</text></text>
          <picker 
            mode="date" 
            @change="onRecordTimeChange"
            :value="formData.recordDate"
            class="picker"
          >
            <view class="picker-text">{{formData.recordDate || '请选择健康日期'}}</view>
          </picker>
        </view>

        <view class="form-item">
          <text class="label">备注</text>
          <textarea 
            v-model="formData.remark" 
            placeholder="请输入备注信息" 
            class="textarea"
            maxlength="200"
          />
        </view>
      </view>
    </view>
    
    <!-- 底部保存按钮 -->
    <view class="bottom-save-section">
      <button class="save-btn" @click="saveRecord">保存</button>
    </view>
  </view>
</template>

<script>
import { getPetList } from '@/api/pet.js'
import { getUserId, checkAndRedirectToLogin } from '@/utils/auth.js'
import { addHealthRecord } from '@/api/health.js'
import { getDictData } from '@/api/dict.js'

export default {
  data() {
    return {
      pets: [],
      selectedPet: null,
      petIndex: -1,
      preSelectedPetId: null,
      formData: {
        petId: '',
        recordType: '',
        title: '',
        status: '已完成', // 默认为已完成状态
        remark: '',
        reminderId: '', // 提醒ID字段
        recordDate: new Date().toISOString().split('T')[0] // 记录日期字段，默认为当前日期，只保留年月日
      },

      recordTypes: [],
      recordTypeLabels: [],
      statusOptions: [],
      typeIndex: -1,
      statusIndex: 1 // 默认选择已完成状态
    }
  },
  async onLoad(options) {

    
    // 检查认证状态
    const token = uni.getStorageSync('token')
    const userId = uni.getStorageSync('userId')
    
    if (!token || !userId) {
      uni.showToast({
        title: '请先登录',
        icon: 'none'
      })
      setTimeout(() => {
        uni.navigateTo({
          url: '/pages/login/login'
        })
      }, 1500)
      return
    }
    
    // 保存传入的petId参数
    if (options.petId) {
      this.preSelectedPetId = options.petId

    } else {

    }
    
    // 保存传入的reminderId参数
    if (options.reminderId) {
      this.formData.reminderId = options.reminderId
    }
    
    // 处理传入的日期参数
    if (options.recordDate || options.date) {
      this.formData.recordDate = decodeURIComponent(options.recordDate || options.date || '')
      console.log('Health Add - Set recordDate from options:', this.formData.recordDate)
    }
    
    // 处理重新生成传递过来的健康记录数据
    if (options.recordType || options.type) {
      this.formData.recordType = decodeURIComponent(options.recordType || options.type || '')
      // 设置对应的索引
      const typeIndex = this.recordTypes.indexOf(this.formData.recordType)
      if (typeIndex !== -1) {
        this.typeIndex = typeIndex
      }
    }
    
    if (options.content || options.title) {
      this.formData.title = decodeURIComponent(options.content || options.title || '')
    }
    


    
    if (options.status) {
      // 忽略传入的状态参数，始终保持默认的已完成状态
      this.formData.status = '已完成'
      this.statusIndex = 1
    }
    
    if (options.remark) {
      this.formData.remark = decodeURIComponent(options.remark || '')
    }
    

    
    this.loadPets()
    // 确保字典数据加载完成后再继续
    await this.loadDictData()
  },
  methods: {
    async loadPets() {
      try {
        // 使用统一的认证检查函数
        if (!checkAndRedirectToLogin('请先登录')) {
          return
        }
        
        const userId = getUserId()
        const response = await getPetList(userId)
        
        if (response && response.code === 200) {
          const petData = response.rows || response.data || []
          this.pets = petData
          
          // 如果有预选的petId，自动选中对应的宠物
          if (this.preSelectedPetId) {
            
            const petIndex = this.pets.findIndex(pet => {
              // 尝试多种匹配方式
              const match1 = pet.id == this.preSelectedPetId // 宽松匹配
              const match2 = pet.id === this.preSelectedPetId // 严格匹配
              const match3 = String(pet.id) === String(this.preSelectedPetId) // 字符串匹配
      
              return match1 || match2 || match3
            })
            
      
            if (petIndex !== -1) {
              this.petIndex = petIndex
              this.selectedPet = this.pets[petIndex]
              this.formData.petId = this.selectedPet.id
        
            } else {

            }
          }
        } else {
          this.pets = []
          uni.showToast({
            title: response?.msg || '加载宠物列表失败',
            icon: 'none'
          })
        }
      } catch (error) {
    
        this.pets = []
        uni.showToast({
          title: '加载宠物列表失败',
          icon: 'none'
        })
      }
    },
    
    onPetChange(e) {
      this.petIndex = e.detail.value
      this.selectedPet = this.pets[this.petIndex]
      this.formData.petId = this.selectedPet.id
    },
    
    onTypeChange(e) {
      this.typeIndex = e.detail.value
      this.formData.recordType = this.recordTypeLabels[e.detail.value]
    },
    
    onRecordTimeChange(e) {
      this.formData.recordDate = e.detail.value
    },
    

    

    
    goBack() {
      uni.navigateBack()
    },
    
    validateForm() {
      if (!this.formData.petId) {
        uni.showToast({
          title: '请选择宠物',
          icon: 'none'
        })
        return false
      }
      
      if (!this.formData.recordType) {
        uni.showToast({
          title: '请选择记录类型',
          icon: 'none'
        })
        return false
      }
      
      if (!this.formData.title.trim()) {
        uni.showToast({
          title: '请输入记录内容',
          icon: 'none'
        })
        return false
      }
      
      if (!this.formData.recordDate) {
        uni.showToast({
          title: '请选择记录时间',
          icon: 'none'
        })
        return false
      }
      
      return true
    },
    
    async saveRecord() {
      if (!this.validateForm()) {
        return
      }
      
      this.saveHealthRecord()
    },
    
    async saveHealthRecord() {
      // 使用统一的认证检查函数
      if (!checkAndRedirectToLogin('请先登录')) {
        return
      }
      
      uni.showLoading({
        title: '保存中...'
      })
      
      try {

        
        // 准备提交数据
        // recordDate只包含日期部分，格式为 yyyy-MM-DD，避免时区影响
        let formattedRecordDate = this.formData.recordDate;
        if (formattedRecordDate && formattedRecordDate.includes(' ')) { // 如果包含时间部分，只取日期部分
          formattedRecordDate = formattedRecordDate.split(' ')[0];
        }
        
        const submitData = {
          petId: this.formData.petId,
          type: this.formData.recordType,
          content: this.formData.title,
          status: this.formData.status === '已完成' ? '1' : '0',
          reminderId: this.formData.reminderId, // 提醒ID字段
          recordDate: formattedRecordDate // 记录日期字段
        }
        
        // 使用健康API添加记录
        const response = await addHealthRecord(submitData)
        
        uni.hideLoading()
        
  
        
        // 检查响应数据
        if (response && response.code === 200) {
          uni.showToast({
            title: '保存成功',
            icon: 'success'
          })
          
          // 发送事件通知列表页面刷新
          uni.$emit('healthrecordupdated')
          
          // 延迟返回上一页
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else {
          // 业务逻辑错误
          const errorMsg = response?.msg || response?.message || '保存失败'
    
          uni.showToast({
            title: errorMsg,
            icon: 'none'
          })
        }
      } catch (error) {
        uni.hideLoading()
  
        uni.showToast({
          title: '网络错误',
          icon: 'none'
        })
      }
    },
    
    async loadDictData() {
    try {

      
      // 加载记录类型字典
      const recordTypeResponse = await getDictData('pet_health_type')
      if (recordTypeResponse && recordTypeResponse.code === 200) {
        this.recordTypes = recordTypeResponse.data || []
        this.recordTypeLabels = this.recordTypes.map(item => item.dictLabel)
      } else {
        // 默认值
        this.recordTypes = [
          { dictLabel: '疫苗', dictValue: 'vaccine' },
          { dictLabel: '驱虫', dictValue: 'deworming' },
          { dictLabel: '体检', dictValue: 'checkup' },
          { dictLabel: '其他', dictValue: 'other' }
        ]
        this.recordTypeLabels = this.recordTypes.map(item => item.dictLabel)
      }
      

      
      // 加载状态字典
      const statusResponse = await getDictData('pet_health_status')
      if (statusResponse && statusResponse.code === 200) {
        this.statusOptions = statusResponse.data || []
      } else {
        // 默认值
        this.statusOptions = [
          { dictLabel: '待处理', dictValue: 'pending' },
          { dictLabel: '已完成', dictValue: 'completed' },
          { dictLabel: '已逾期', dictValue: 'overdue' }
        ]
      }
      

      
      if (this.statusOptions.length > 0) {
        this.formData.status = this.statusOptions[1].dictLabel || '已完成'
      }
      

      
    } catch (error) {
      // 使用默认值
      this.recordTypes = [
        { dictLabel: '疫苗', dictValue: 'vaccine' },
        { dictLabel: '驱虫', dictValue: 'deworming' },
        { dictLabel: '体检', dictValue: 'checkup' },
        { dictLabel: '其他', dictValue: 'other' }
      ]
      this.recordTypeLabels = this.recordTypes.map(item => item.dictLabel)
      

      
      this.statusOptions = [
        { dictLabel: '待处理', dictValue: 'pending' },
        { dictLabel: '已完成', dictValue: 'completed' },
        { dictLabel: '已逾期', dictValue: 'overdue' }
      ]
    }
  }
}
}
</script>

<style scoped>
.container {
  background: #f5f5f5;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.nav-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  background: #fff;
  border-bottom: 1px solid #eee;
}

.back-btn {
  background: #007AFF;
  color: #fff;
  border: none;
  border-radius: 8rpx;
  padding: 10rpx 30rpx;
  font-size: 28rpx;
}

.title {
  font-size: 32rpx;
  font-weight: bold;
}

.form-container {
  padding: 20rpx;
  flex-grow: 1; /* Allow form to grow and take available space */
  position: relative;
  z-index: 1;
}

/* 底部保存按钮区域 */
.bottom-save-section {
  padding: 20rpx;
  background: #fff;
  border-top: 1px solid #eee;
}

.save-btn {
  width: 100%;
  background: #007AFF;
  color: #fff;
  border: none;
  border-radius: 8rpx;
  padding: 20rpx;
  font-size: 32rpx;
  font-weight: bold;
}

.form-section {
  background: #fff;
  border-radius: 15rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.form-item {
  margin-bottom: 30rpx;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
}

.form-item:last-child {
  margin-bottom: 0;
}

.label {
  display: flex;
  align-items: center;
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
  width: 180rpx;
  flex-shrink: 0;
  margin-right: 20rpx;
}

.required {
  color: #ff0000;
  margin-left: 4rpx;
  font-weight: bold;
}

.input, .picker, .textarea {
  flex: 1;
  min-height: 36rpx;
  padding: 20rpx;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  background: #fff;
}

.picker-text {
  color: #333;
}

.textarea {
  height: 120rpx;
  resize: none;
}

.content-textarea {
  height: 300rpx; /* 内容使用较大的高度 */
  min-height: 36rpx;
  line-height: 1.4;
}

.input:focus, .textarea:focus {
  border-color: #007AFF;
  outline: none;
  box-shadow: 0 0 0 2px rgba(0, 122, 255, 0.2);
}
</style>